import React from "react"
import styles from "./index.module.scss"
import logo from "../../assets/images/login_logo.png"
import { Form, Input, Checkbox, Button, message } from "antd"
import { useDispatch } from "react-redux"
import { LoginPackages } from "../../store/action/login"
import { useNavigate } from "react-router-dom"

function Login() {
  const [form] = Form.useForm()
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const onCheck = async () => {
    try {
      const values = await form.validateFields()
      dispatch(LoginPackages({ mobile: values.mobile, code: values.code }))
      // 弹出提示 // 跳转页面
      message.success("登录成功", 1, () => {
        navigate("/home")
      })
    } catch (errorInfo) {
      console.log("Failed:", errorInfo)
    }
  }
  return (
    <div className={styles.login}>
      <div className={styles.login_cart}>
        <img className={styles.login_logo} src={logo} alt=""></img>
        <Form
          name="basic"
          form={form}
          initialValues={{
            mobile: "13911111111",
            code: "246810",
            remeber: true
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: "手机号为必填项!" },
              {
                pattern: new RegExp(
                  /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
                ),
                message: "手机号码格式不正确"
              }
            ]}
          >
            <Input placeholder="请输入手机号码" size="large" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: "验证码为必填项!" },
              {
                pattern: new RegExp(/^[0-9]\d{5}$/),
                message: "验证码格式不正确"
              }
            ]}
          >
            <Input placeholder="请输入验证码" size="large" />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) => {
                  if (value === true) return Promise.resolve()
                  else return Promise.reject(new Error("请勾选我已阅读并同意"))
                }
              }
            ]}
          >
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>

          <Form.Item style={{ margin: 0 }}>
            <Button
              className={styles.login_but}
              type="primary"
              htmlType="submit"
              size="large"
              onClick={onCheck}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
